package net.guerlab.smart.wx.api.autoconfig;

import lombok.AllArgsConstructor;
import net.guerlab.commons.exception.ApplicationException;
import net.guerlab.smart.wx.api.WxMpTemplateMsgApi;
import net.guerlab.smart.wx.api.feign.FeignWxMpTemplateMsgApi;
import net.guerlab.smart.wx.core.message.SendMsgResponse;
import net.guerlab.smart.wx.core.message.WxMpTemplateMessageSendRequest;
import net.guerlab.web.result.Result;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * @author guer
 */
@Configuration
@AutoConfigureAfter(WxMpTemplateMsgApiLocalServiceAutoConfigure.class)
public class WxMpTemplateMsgApiFeignAutoConfigure {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Bean
    @ConditionalOnMissingBean(WxMpTemplateMsgApi.class)
    public WxMpTemplateMsgApi wxMpTemplateMsgApiFeignWrapper(FeignWxMpTemplateMsgApi api) {
        return new WxMpTemplateMsgApiFeignWrapper(api);
    }

    @AllArgsConstructor
    private static class WxMpTemplateMsgApiFeignWrapper implements WxMpTemplateMsgApi {

        private final FeignWxMpTemplateMsgApi api;

        @Override
        public Map<String, SendMsgResponse> sendMsg(String appId, WxMpTemplateMessageSendRequest request) {
            Result<Map<String, SendMsgResponse>> result = api.sendMsg(appId, request);

            if (result.isStatus()) {
                return result.getData();
            }

            throw new ApplicationException(result.getMessage(), result.getErrorCode());
        }
    }

}
